﻿/*************************************************
 * (C) 2011 Charles Allen, all rights reserved
 * 
 * This work is licensed under the GNU LGPL v3.0 http://www.gnu.org/licenses/lgpl-3.0.txt
 * 
 * There is no warranty, express or implied, on this software. The user assumes all risk associated with the use of this software.
 * 
                    GNU LESSER GENERAL PUBLIC LICENSE
                       Version 3, 29 June 2007

 Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
 Everyone is permitted to copy and distribute verbatim copies
 of this license document, but changing it is not allowed.


  This version of the GNU Lesser General Public License incorporates
the terms and conditions of version 3 of the GNU General Public
License, supplemented by the additional permissions listed below.

  0. Additional Definitions.

  As used herein, "this License" refers to version 3 of the GNU Lesser
General Public License, and the "GNU GPL" refers to version 3 of the GNU
General Public License.

  "The Library" refers to a covered work governed by this License,
other than an Application or a Combined Work as defined below.

  An "Application" is any work that makes use of an interface provided
by the Library, but which is not otherwise based on the Library.
Defining a subclass of a class defined by the Library is deemed a mode
of using an interface provided by the Library.

  A "Combined Work" is a work produced by combining or linking an
Application with the Library.  The particular version of the Library
with which the Combined Work was made is also called the "Linked
Version".

  The "Minimal Corresponding Source" for a Combined Work means the
Corresponding Source for the Combined Work, excluding any source code
for portions of the Combined Work that, considered in isolation, are
based on the Application, and not on the Linked Version.

  The "Corresponding Application Code" for a Combined Work means the
object code and/or source code for the Application, including any data
and utility programs needed for reproducing the Combined Work from the
Application, but excluding the System Libraries of the Combined Work.

  1. Exception to Section 3 of the GNU GPL.

  You may convey a covered work under sections 3 and 4 of this License
without being bound by section 3 of the GNU GPL.

  2. Conveying Modified Versions.

  If you modify a copy of the Library, and, in your modifications, a
facility refers to a function or data to be supplied by an Application
that uses the facility (other than as an argument passed when the
facility is invoked), then you may convey a copy of the modified
version:

   a) under this License, provided that you make a good faith effort to
   ensure that, in the event an Application does not supply the
   function or data, the facility still operates, and performs
   whatever part of its purpose remains meaningful, or

   b) under the GNU GPL, with none of the additional permissions of
   this License applicable to that copy.

  3. Object Code Incorporating Material from Library Header Files.

  The object code form of an Application may incorporate material from
a header file that is part of the Library.  You may convey such object
code under terms of your choice, provided that, if the incorporated
material is not limited to numerical parameters, data structure
layouts and accessors, or small macros, inline functions and templates
(ten or fewer lines in length), you do both of the following:

   a) Give prominent notice with each copy of the object code that the
   Library is used in it and that the Library and its use are
   covered by this License.

   b) Accompany the object code with a copy of the GNU GPL and this license
   document.

  4. Combined Works.

  You may convey a Combined Work under terms of your choice that,
taken together, effectively do not restrict modification of the
portions of the Library contained in the Combined Work and reverse
engineering for debugging such modifications, if you also do each of
the following:

   a) Give prominent notice with each copy of the Combined Work that
   the Library is used in it and that the Library and its use are
   covered by this License.

   b) Accompany the Combined Work with a copy of the GNU GPL and this license
   document.

   c) For a Combined Work that displays copyright notices during
   execution, include the copyright notice for the Library among
   these notices, as well as a reference directing the user to the
   copies of the GNU GPL and this license document.

   d) Do one of the following:

       0) Convey the Minimal Corresponding Source under the terms of this
       License, and the Corresponding Application Code in a form
       suitable for, and under terms that permit, the user to
       recombine or relink the Application with a modified version of
       the Linked Version to produce a modified Combined Work, in the
       manner specified by section 6 of the GNU GPL for conveying
       Corresponding Source.

       1) Use a suitable shared library mechanism for linking with the
       Library.  A suitable mechanism is one that (a) uses at run time
       a copy of the Library already present on the user's computer
       system, and (b) will operate properly with a modified version
       of the Library that is interface-compatible with the Linked
       Version.

   e) Provide Installation Information, but only if you would otherwise
   be required to provide such information under section 6 of the
   GNU GPL, and only to the extent that such information is
   necessary to install and execute a modified version of the
   Combined Work produced by recombining or relinking the
   Application with a modified version of the Linked Version. (If
   you use option 4d0, the Installation Information must accompany
   the Minimal Corresponding Source and Corresponding Application
   Code. If you use option 4d1, you must provide the Installation
   Information in the manner specified by section 6 of the GNU GPL
   for conveying Corresponding Source.)

  5. Combined Libraries.

  You may place library facilities that are a work based on the
Library side by side in a single library together with other library
facilities that are not Applications and are not covered by this
License, and convey such a combined library under terms of your
choice, if you do both of the following:

   a) Accompany the combined library with a copy of the same work based
   on the Library, uncombined with any other library facilities,
   conveyed under the terms of this License.

   b) Give prominent notice with the combined library that part of it
   is a work based on the Library, and explaining where to find the
   accompanying uncombined form of the same work.

  6. Revised Versions of the GNU Lesser General Public License.

  The Free Software Foundation may publish revised and/or new versions
of the GNU Lesser General Public License from time to time. Such new
versions will be similar in spirit to the present version, but may
differ in detail to address new problems or concerns.

  Each version is given a distinguishing version number. If the
Library as you received it specifies that a certain numbered version
of the GNU Lesser General Public License "or any later version"
applies to it, you have the option of following the terms and
conditions either of that published version or of any later version
published by the Free Software Foundation. If the Library as you
received it does not specify a version number of the GNU Lesser
General Public License, you may choose any version of the GNU Lesser
General Public License ever published by the Free Software Foundation.

  If the Library as you received it specifies that a proxy can decide
whether future versions of the GNU Lesser General Public License shall
apply, that proxy's public statement of acceptance of any version is
permanent authorization for you to choose that version for the
Library.

 *************************************************/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
using System.Threading.Tasks;

namespace ACMLGPU
{
    /* General Control Functions
     *****************************
     * Provides general ACML wrappers for getting info on ACML.
     *****************************/
    public static class Control
    {
        public const string ACMLDLL = "libacml_mp_dll.dll";
        #region DLL Importing Control Defines
        [DllImport(Control.ACMLDLL)]
        static extern void acmlsetnumthreads([In] int numthreads);
        [DllImport(Control.ACMLDLL)]
        static extern int acmlgetnumprocs();
        [DllImport(Control.ACMLDLL)]
        static extern int acmlgetnumthreads();
        [DllImport(Control.ACMLDLL)]
        static extern int acmlgetmaxthreads();
        [DllImport(Control.ACMLDLL)]
        static extern void acmlversion(ref int major, ref int minor, ref int patch);
        [DllImport(Control.ACMLDLL)]
        #endregion
        static extern void acmlinfo();
        public static void setnumthreads(int numthreads)
        {
            acmlsetnumthreads(numthreads);
        }
        public static int getnumprocs()
        {
            return acmlgetnumprocs();
        }
        public static int getnumthreads()
        {
            return acmlgetnumthreads();
        }
        public static int getmaxthreads()
        {
            return acmlgetmaxthreads();
        }
        public static void version(ref int major, ref int minor, ref int patch)
        {
            acmlversion(ref major, ref minor, ref patch);
        }
        public static void info()
        {
            acmlinfo();
        }
    }
    namespace Math
    {
        public unsafe class General
        {
            #region GeneralDllImports
            
            [DllImport(@"amdlibm.dll")]
            static extern float amd_powf([In] float x, [In] float y);
            [DllImport(@"amdlibm.dll")]
            static extern double amd_pow([In] double x, [In] double y);
            [DllImport(@"amdlibm.dll")]
            static extern float amd_floorf(float x);
            [DllImport(@"amdlibm.dll")]
            static extern double amd_floor(double x);

            [DllImport(Control.ACMLDLL)]
            static extern void sgtsv([In] int n, [In] int nrhs, [In, Out] float* low, [In, Out] float* diag, [In, Out] float* up, [In, Out] float* b, [In] int ldb, [Out] int* info);
            
            [DllImport(@"libacml_mv_dll.dll")]
            static extern double fastexp(double x);
            [DllImport(@"libacml_mv_dll.dll")]
            static extern double fastlog(double x);
            [DllImport(@"libacml_mv_dll.dll")]
            static extern double fastlog10(double x);
            [DllImport(@"libacml_mv_dll.dll")]
            static extern double fastlog2(double x);
            [DllImport(@"libacml_mv_dll.dll")]
            static extern double fastpow(double x, double y);
            [DllImport(@"libacml_mv_dll.dll")]
            static extern double fastsin(double x);
            [DllImport(@"libacml_mv_dll.dll")]
            static extern double fastcos(double x);
            [DllImport(@"libacml_mv_dll.dll")]
            static extern void fastsincos(double  x, double *y, double *z);

            [DllImport(@"libacml_mv_dll.dll")]
            static extern float fastexpf(float x);
            [DllImport(@"libacml_mv_dll.dll")]
            static extern float fastlogf(float x);
            [DllImport(@"libacml_mv_dll.dll")]
            static extern float fastlog10f(float x);
            [DllImport(@"libacml_mv_dll.dll")]
            static extern float fastlog2f(float x);
            [DllImport(@"libacml_mv_dll.dll")]
            static extern float fastpowf(float x, float y);
            [DllImport(@"libacml_mv_dll.dll")]
            static extern float fastcosf(float x);
            [DllImport(@"libacml_mv_dll.dll")]
            static extern float fastsinf(float x);
            [DllImport(@"libacml_mv_dll.dll")]
            static extern void fastsincosf(float x, float *y, float *z);
            #endregion
            #region Trig
            public static double Cos(double x)
            {
                return fastcos(x);
            }
            public static double Sin(double x)
            {
                return fastsin(x);
            }
            public static float Cos(float x)
            {
                return fastcosf(x);
            }
            public static float Sin(float x)
            {
                return fastsinf(x);
            }
            #endregion

            #region Other Math
            public static double Floor(double x)
            {
                return (int)amd_floor(x);
            }
            public static float Floor(float x)
            {
                return (int)amd_floorf(x);
            }
            public static float Pow(float x, float y)
            {
                return amd_powf(x, y);
            }
            public static double Pow(double x, double y)
            {
                return amd_pow(x, y);
            }
            #endregion

            #region Cubic Spline
            /* Cubic Spline Interpolation
             **************************************************************************
             * This one doesn't work yet...
             * It is intended to be a Spline calculator for equal-spaced x steps.
             **************************************************************************/
            public unsafe static Vector Spline(float xStart, float xStep, Vector yKnown, Vector xNew)
            {
                #if !DEBUG
                Exception e = new Exception("ERROR: Equal-spaced spline not functional");
                throw e;
                #endif

                // Calculates Cubic Spline interpolation for equal-spaced X values
                int n = yKnown.Length;
                Vector B = new Vector(n);
                Vector X = new Vector(n);
                int Info;
                Vector DL = new Vector(n - 2);
                Vector D = new Vector(n);
                Vector DU = new Vector(n - 2);
                float H = xStep;
                Vector retVal = new Vector(xNew.Length);
                const float inv3 = 1 / 3.0f;

                int location = 0;

                Console.WriteLine("{0}", location++);

                B[0] = 0;
                B[B.Length - 1] = 0;
                //for (int counter = 1; counter < B.Length - 1; counter++)
                Parallel.For(1, B.Length - 1, counter =>
                {
                    B[counter] = yKnown[counter + 1] - 2.0f * yKnown[counter] + yKnown[counter - 1];
                }
                );
                B = B * (6 * Math.General.Pow(H, -2.0f));

                Console.WriteLine("{0}", location++);
                for (int counter = 1; counter < D.Length - 1; counter++)
                {
                    D[counter] = 1.0f;
                }

                Vector.Copy(D, DU, 1, n - 2);
                Vector.Copy(D, DL, 0, n - 3);

                D = D * 4.0f;

                // Natural boundry conditions
                D[0] = 1;
                D[D.Length - 1] = 1;
                Console.WriteLine("{0}", location++);
                // Get the spline segment parameters
                try
                {
                    //sgtsv(n, X.Length, DL.Value, D.Value, DU.Value, B.Value, n, &Info);
                    sgtsv(n, X.Length, DL.Value, D.Value, DU.Value, B.Value, n, &Info);
                }
                catch (Exception ee)
                {
                    throw ee;
                }
                if (Info!=0)
                {
                    Exception ee = new Exception("Solving failed");
                    throw ee;
                }
                Console.WriteLine("{0}", location++);
                //Parallel.For(0, xNew.Length, counter =>
                for (int counter = 0; counter < xNew.Length; counter++)
                {
                    float a, b, c, d, xKnown;
                    // Now figure out which spline we are calculating
                    int splineSegment;
                    splineSegment = (int)System.Math.Floor((xNew[counter] - xStart) / xStep);
                    // Calculate a,b,c,d for a*(x-x1)^3 + b*(x-x2)^2 + c*(x-x3) + d
                    a = (B[splineSegment + 1] - B[splineSegment]) / (6.0f * H);
                    b = B[splineSegment] * 0.5f;
                    c = (yKnown[splineSegment + 1] - yKnown[splineSegment]) / H - (B[splineSegment + 1] * 0.5f - B[splineSegment]) * H * inv3;
                    d = yKnown[splineSegment];

                    xKnown = (xStart + xStart * splineSegment);
                    retVal[counter] = a * Math.General.Pow(xNew[counter] - xKnown, 3.0f) + b * Math.General.Pow(xNew[counter] - xKnown, 2.0f) + c * (xNew[counter] - xKnown) + d;
                }
                //);

                return retVal;
            }

            /* Cubic Spline Interpolation
            **************************************************************************
            * Returns f(xNew) for yKnown = f(xKnown) for some generic function f
            * Uses Natural boundry conditions. (second derivative at endpoints is zero)
            * Does **NOT** extrapolate.
            * If you're having trouble getting good Spline fits, try taking the log of the input vectors (and exp of the output vector).
            **************************************************************************/
            public unsafe static Vector Spline(Vector xKnown, Vector yKnown, Vector xNew)
            {
                // Calculates cubic spline interpolation using natural boundry conditions
                // Quick sanity check
                if (xKnown.Length != yKnown.Length)
                {
                    Exception e = new Exception("Spline interpolation requires X and Y to be the same length");
                    throw e;
                }

                int n = xKnown.Length;
                Vector B = new Vector(n);
                Vector X = new Vector(n);
                int Info;

                // The tri-diagonal matrix elements
                Vector DL = new Vector(n - 1);
                Vector D = new Vector(n);
                Vector DU = new Vector(n - 1);

                Vector H;
                Vector retVal = new Vector(xNew.Length);
                const float inv3 = 1 / 3.0f; // This may or may not actually be useful.

                H = Vector.diff(xKnown);

                B[0] = 0;
                B[B.Length - 1] = 0;

                // Yay .NET v4 !
                Parallel.For(1, B.Length - 1, counter =>
                {
                    B[counter] = (yKnown[counter + 1] - yKnown[counter]) / H[counter] - (yKnown[counter] - yKnown[counter - 1]) / H[counter - 1];
                });
                B = B * 6.0f;

                // This may or may not yield a speed increase... probably not.
                Parallel.For(1, D.Length - 1, counter =>
                    {
                        D[counter] = H[counter] + H[counter - 1];
                    });
                D = D * 2.0f;

                // Natural boundry conditions
                D[0] = 1;
                D[D.Length - 1] = 1;

                Vector.Copy(H, DU);
                Vector.Copy(H, DL, 0, n - 2);
                DU[0] = 0.0f;
                DL[DL.Length - 1] = 0.0f;

                // Get the spline segment parameters
                //
                // ********* This statement that might not be thread-safe if using ACML-GPU
                //
                sgtsv(n,1, DL.Value, D.Value, DU.Value, B.Value, n, &Info);


                if (Info != 0)
                {
                    string s = string.Format("Spline matrix calculation failed with Error {0}", Info);
                    Exception e = new Exception(s);
                    throw e;
                }

                // This may or may not be a speed increase.
                float minx = ACMLGPU.MinMax.Min(xKnown[0], xKnown[xKnown.Length - 1]);
                float maxx = ACMLGPU.MinMax.Max(xKnown[0], xKnown[xKnown.Length - 1]);
                
                
                Parallel.For(0, xNew.Length, counter =>
                {
                    float a, b, c, d;
                    // Now figure out which spline we are calculating
                    // This is a really dumb and simple way to find the segment of interest.
                    // The more astute CS people out there could probably implement a better search algorithm.
                    int splineSegment;
                    if ((xNew[counter] <= maxx) && (xNew[counter] >= minx)) // Make sure we're interpolating
                    {
                        for (splineSegment = 0; splineSegment < xKnown.Length - 1; splineSegment++)
                        {
                            float test1, test2;
                            test1 = xNew[counter] - xKnown[splineSegment];
                            test2 = xNew[counter] - xKnown[splineSegment + 1];
                            if (test1 * test2 <= 0)
                                break;
                        }
                    }
                    else
                    {
                        Exception e = new Exception("Spline can only interpolate, cannot extrapolate");
                        throw e;
                    }

                    // Calculate a,b,c,d for a*(x-x1)^3 + b*(x-x2)^2 + c*(x-x3) + d
                    // There may be a way to better vectorize this part, but I haven't looked into it much.
                    // Since float multiply is usually faster than float divide, I attempted to replace all fixed denominators with multiplications (ex: 0.5f instead of 1/2.0f). Optimization *should* do that for us, but its easy to implement.
                    a = (B[splineSegment + 1] - B[splineSegment]) / (6.0f * H[splineSegment]);
                    b = B[splineSegment] * 0.5f;
                    c = (yKnown[splineSegment + 1] - yKnown[splineSegment]) / H[splineSegment] - (B[splineSegment + 1] * 0.5f + B[splineSegment]) * H[splineSegment] * inv3;
                    d = yKnown[splineSegment];

                    // Do the actual a*(x-x1)^3 + b*(x-x2)^2 + c*(x-x3) + d  cubic spline interpolation
                    retVal[counter] = a * Math.General.Pow(xNew[counter] - xKnown[splineSegment], 3.0f) + b * Math.General.Pow(xNew[counter] - xKnown[splineSegment], 2.0f) + c * (xNew[counter] - xKnown[splineSegment]) + d;
                }
                );

                return retVal;
            }
            #endregion
        }
        public unsafe class Vector : IDisposable
        {
            #region VectorDLLImports
            [DllImport(Control.ACMLDLL)]
            static extern float sdot([In] int n, [In] float *x, [In] int incx, [In] float *y, [In] int incy);
            [DllImport(Control.ACMLDLL)]
            static extern float snrm2([In] int n, [In] float *x, [In] int incx);
            [DllImport(Control.ACMLDLL)]
            static extern void sscal([In]int n, [In] float alpha, [In, Out]float *x, [In] int incx);
            [DllImport(Control.ACMLDLL)]
            static extern void srandinitialize([In] int genid, [In] int subid, [In] int *seed, [In, Out] int *lseed, [Out] int *state, [In, Out] int *lstate, [Out] int *info);

            [DllImport(Control.ACMLDLL)]
            static extern void scopy([In] int n, [In] float *x, [In] int incx, [Out] float *y, [In] int incy);

            [DllImport(@"libacml_mv_dll.dll")]
            static extern void vrsa_expf([In] int n, [In] float *input, [Out] float *output);
            [DllImport(@"libacml_mv_dll.dll")]
            static extern void vrsa_logf([In] int n, [In] float *input, [Out] float *output);
            [DllImport(@"libacml_mv_dll.dll")]
            static extern void vrsa_log10f([In] int n, [In] float *input, [Out] float *output);
            [DllImport(@"libacml_mv_dll.dll")]
            static extern void vrsa_log2f([In] int n, [Out] float *input, [Out] float *output);
            [DllImport(@"libacml_mv_dll.dll")]
            static extern void vrsa_powf([In] int n, [In] float *input, [In] float *raised_power, [Out] float *output);
            [DllImport(@"libacml_mv_dll.dll")]
            static extern void vrsa_powxf([In] int n, [In] float *input, [In] float raised_power, [Out] float *output);
            [DllImport(@"libacml_mv_dll.dll")]
            static extern void vrsa_sinf([In] int n, [In] float *input, [Out] float *output);
            [DllImport(@"libacml_mv_dll.dll")]
            static extern void vrsa_cosf([In] int n, [In] float *input, [Out] float *output);
            [DllImport(@"libacml_mv_dll.dll")]
            static extern void vrsa_sincosf([In] int n, [In] float *input, [Out] float *sin_result, [Out] float *cos_result); // TODO: implement this
            #endregion
            private bool disposed = false;
            public Vector(int sz)
            {
                /**** Tests show the alloc is aligned!
                const long ALLIGNMENT_BYTES = 16;
                HeapStart = Marshal.AllocHGlobal(sz * sizeof(float) + (int)ALLIGNMENT_BYTES); // Allocate an extra 16 bytes
                ulong hs = (ulong)HeapStart;
                // Allign as requested
                Value = (float*)(hs + (ALLIGNMENT_BYTES - (hs % ALLIGNMENT_BYTES)));
                ulong adj = (ALLIGNMENT_BYTES - (hs % ALLIGNMENT_BYTES));
                Console.WriteLine("mod {0} {1}", hs.ToString("X"), (hs>>4).ToString("X"));
                Console.WriteLine("Starting at {0} from {1} with adj {2}", ((IntPtr)Value).ToString("X"), HeapStart.ToString("X"), adj.ToString("X"));
                 */
                HeapStart = Marshal.AllocHGlobal(sz * sizeof(float));
                Value = (float*)HeapStart;
                Length = sz;
            }
            ~Vector()
            {
                Dispose(false);
            }
            public void Dispose()
            {
                Dispose(true);
                GC.SuppressFinalize(this);
            }
            protected virtual void Dispose(bool disposing)
            {
                if (!disposed)
                {
                    if (disposing)
                    {
                        // Free managed resources
                    }

                    // Free unmanaged resources
                    if (this.HeapStart != IntPtr.Zero)
                    {
                        Marshal.FreeHGlobal(this.HeapStart);
                        this.HeapStart = IntPtr.Zero;
                    }
                    disposed = true;
                }
            }
            public float* Value;// Alligned pointer contained within HeapStart
            IntPtr HeapStart;
            public int Length;

            #region Overloaded operators
            public float this[int i]
            {
                get {
#if DEBUG
                    if ((i > this.Length - 1) || (i < 0))
                    {
                        Exception e = new Exception("Index out of bounds");
                        throw e;
                    }
#endif
                    return this.Value[i]; 
                }
                set {
#if DEBUG
                    if ((i > this.Length - 1) || (i < 0))
                    {
                        Exception e = new Exception("Index out of bounds");
                        throw e;
                    } 
#endif
                    this.Value[i] = (float)value;
                }
            }
            /* Dot Product */
            public static float operator *(Vector V1, Vector V2)
            {
                return sdot(V1.Length, V1.Value, 1, V2.Value, 1);
            }
            public static Vector operator *(Vector V1, float scl)
            {
                Vector retV;
                retV = new Vector(V1.Length);
                scopy(retV.Length, V1.Value, 1, retV.Value, 1);
                sscal(retV.Length, scl, retV.Value, 1);
                return retV;
            }
            public static Vector operator /(Vector V1, float scl)
            {
                Vector retV;
                retV = new Vector(V1.Length);
                scopy(retV.Length, V1.Value, 1, retV.Value, 1);
                sscal(retV.Length, 1.0f/scl, retV.Value, 1);
                return retV;
            }
            public static implicit operator Vector(float[] ival)
            {
                Vector retV = new Vector(ival.Length);
                Vector.Copy(ival, retV);
                return retV;
            }
            public static implicit operator float[](Vector ival)
            {
                float[] retV = new float[ival.Length];
                Vector.Copy(ival, retV);
                return retV;
            }
            #endregion

            public static void Copy(Vector source, float[] dest)
            {
                Int32 len = source.Length;
                #if DEBUG
                if (source.Length != dest.Length)
                {
                    Exception e = new Exception("Vector copy source and destination must be the same size");
                    throw e;
                }
                #endif
                fixed (float* destp = &dest[0])
                {
                    scopy(len, source.Value, 1, destp, 1);
                }
            }
            public static void Copy(float[] source, Vector dest)
            {
                Int32 len = source.Length;
                #if DEBUG
                if (source.Length != dest.Length)
                {
                    Exception e = new Exception("Vector copy source and destination must be the same size");
                    throw e;
                }
                #endif
                fixed (float* sourcep = &source[0])
                {
                    scopy(len, sourcep, 1, dest.Value, 1);
                }
            }

            public static void Copy(Vector source, Vector dest)
            {
                #if DEBUG
                if (source.Length != dest.Length)
                {
                    Exception e = new Exception("Vector copy source and destination must be the same size");
                    throw e;
                }
                #endif
                Copy(source, dest, source.Length);
                /*(Parallel.For(0, dest.Length, counter =>
                    {
                        dest[counter] = source[counter];
                    });*/
            }
            public static void Copy(Vector source, Vector dest, Int32 len)
            {
                #if DEBUG
                if ((source.Length < len) || (dest.Length < len))
                {
                    Exception e = new Exception("Vector copy source and destination be able to hold entire copy length");
                    throw e;
                }
                #endif
                len = MinMax.Min(source.Length, dest.Length, len);
                scopy(len, source.Value, 1, dest.Value, 1);
            }
            public static void Copy(Vector source, Vector dest, Int32 iStart, Int32 iEnd)
            {
                if ((iEnd < 0) || (iStart < 0))
                {
                    Exception e = new Exception("Indexed Vector indecies must be positive");
                    throw e;
                }
                if((iEnd >= source.Length) || (iStart >= source.Length))
                {
                    Exception e = new Exception("Indexed Vector indecies out of bounds");
                    throw e;
                }
                if((iEnd - iStart + 1) > dest.Length) 
                {
                    Exception e = new Exception("Indexed Vector copy destination too small");
                    throw e;
                }
                scopy(iEnd - iStart + 1, &source.Value[iStart], 1, dest.Value, 1);
            }
            #region Vector Math
            public static Vector Log(Vector V1)
            {
                Vector retV = new Vector(V1.Length);
                vrsa_logf(V1.Length, V1.Value, retV.Value);
                return retV;
            }
            public static Vector Exp(Vector V1)
            {
                Vector retV = new Vector(V1.Length);
                vrsa_expf(V1.Length, V1.Value, retV.Value);
                return retV;
            }
            public static Vector Log10(Vector V1)
            {
                Vector retV = new Vector(V1.Length);
                vrsa_log10f(V1.Length, V1.Value, retV.Value);
                return retV;
            }
            public static Vector Log2(Vector V1)
            {
                Vector retV = new Vector(V1.Length);
                vrsa_log2f(V1.Length, V1.Value, retV.Value);
                return retV;
            }
            public static Vector Sin(Vector V1)
            {
                Vector retV = new Vector(V1.Length);
                vrsa_sinf(V1.Length, V1.Value, retV.Value);
                return retV;
            }
            public static Vector Cos(Vector V1)
            {
                Vector retV = new Vector(V1.Length);
                vrsa_cosf(V1.Length, V1.Value, retV.Value);
                return retV;
            }
            public static Vector Pow(Vector V1, Vector raised_power)
            {
                Vector retV = new Vector(V1.Length);
                vrsa_powf(V1.Length, V1.Value, raised_power.Value, retV.Value);
                return retV;
            }
            public static Vector Pow(Vector V1, float raised_power)
            {
                Vector retV = new Vector(V1.Length);
                vrsa_powxf(V1.Length, V1.Value, raised_power, retV.Value);
                return retV;
            }
            #endregion
            public static Vector diff(Vector X)
            {
                Vector retV = new Vector(X.Length - 1);

                for (int counter = 0; counter < retV.Length; counter++)// =>
                {
                    retV.Value[counter] = X.Value[counter + 1] - X.Value[counter];
                }//) ;

                return retV;
            }
            public static float trapz(Vector X, Vector Y)
            {
                return diff(X)*HalfValue(Y);
            }
            public static Vector HalfValue(Vector V1)
            {
                Vector retV = new Vector(V1.Length - 1);

                for (int counter = 0; counter < retV.Length; counter++)
                {
                    retV.Value[counter] = (V1.Value[counter] + V1.Value[counter + 1]);
                }
                sscal(retV.Length, 0.5f, retV.Value, 1);
                return retV;
            }
            public Vector Normalized()
            {
                Vector retV = new Vector(this.Length);
                float norm;
                norm = snrm2(retV.Length, retV.Value, 1);
                sscal(retV.Length, 1 / norm, retV.Value, 1);
                return retV;
            }
            public void Randomize()
            {
                Random rndnum = new Random();
                for (int counter = 0; counter < this.Length; counter++)
                {
                    this.Value[counter] = (float)rndnum.NextDouble();
                }
            }
        }
        public unsafe class Matrix : Vector
        {
            // NOTE: Matrix elements are in Column-Major order,
            // Therefore
            //  [a b]
            //  [c d]
            // would be {a c b d} in memory
            //
            // r and c are also zero-based, so Matrix[1,1] above would be d
            // Matrix[0,1] would be c
            // Matrix[1,0] would be b
            #region MatrixDlls
            [DllImport(Control.ACMLDLL)]
            static extern void sgemm([In] char transa, [In] char transb, [In]int m, [In]int n, [In]int k, [In]float alpha, [In, Out]float *a, [In]int lda, [In, Out]float *b, [In]int ldb, [In]float beta, [In, Out]float *c, [In]int ldc);
            [DllImport(Control.ACMLDLL)]
            static extern void sgemv([In] char transa, [In] int m, [In] int n, [In] float alpha, [In, Out] float *a, [In]int lda, [In, Out]float *x, [In]int incx, [In]float beta, [In, Out]float *y, [In] int incy);
            [DllImport(Control.ACMLDLL)]
            static extern void sgels([In] char trans, [In] int m, [In] int n, [In] int nrhs, [In, Out] float* a, [In] int lda, [In, Out] float* b, [In] int ldb, [In, Out] int* info);
            #endregion
            public Matrix(int r, int c) : base(r*c)
            {
                this.clen = r;//length of column is number of rows
                this.rlen = c;
            }
            int clen; // Length of columns, number of rows
            int rlen; // Length of rows, number of columns
            public float this[int c, int r]
            {
                get { return base[c*this.clen + r]; }
                set { base[c*this.clen + r] = (float)value; }
            }
            public static Vector operator *(Matrix M1, Vector V1)
            {
                Vector retV;
                retV = new Vector(M1.clen);
                
                sgemv('N',M1.clen,M1.rlen,0.0f,M1.Value,M1.clen,V1.Value,1,1.0f,retV.Value,1);
                return retV;
            }
            public static Matrix operator *(Matrix M1, Matrix M2)
            {
                Matrix retVal;
                int m,n,k;
                m=M1.clen;
                n=M2.rlen;
                k=M1.rlen;
                if (M1.rlen != M2.clen)
                {
                    Exception e = new Exception("Incompatible matrix dimensions for multiplication");
                    throw e;
                }
                retVal = new Matrix(m, n);
                sgemm('N', 'N', m, n, k, 1, M1.Value, M1.clen, M2.Value, M2.clen, 1, retVal.Value, retVal.clen);
                return retVal;
            }
            public int[] Size()
            {
                int[] retVal = new int[2];
                retVal[0]=this.rlen; // Row length = num columns
                retVal[1]=this.clen; // Column length = num rows
                return retVal;
            }
        }
    }
    class MinMax
    {
        /******
         * These functions may or may not actually be a speed increase, depending on the overhead of the call.
         ******/
        #region MinMaxDLLs
        [DllImport(Control.ACMLDLL)]
        static extern float acml_fmax3(float a, float b, float c);
        [DllImport(Control.ACMLDLL)]
        static extern double acml_dmax3(double a, double b, double c);
        [DllImport(Control.ACMLDLL)]
        static extern int acml_imax3(int a, int b, int c);
        [DllImport(Control.ACMLDLL)]
        static extern float acml_fmin3(float a, float b, float c);
        [DllImport(Control.ACMLDLL)]
        static extern double acml_dmin3(double a, double b, double c);
        [DllImport(Control.ACMLDLL)]
        static extern int acml_imin3(int a, int b, int c);     
        [DllImport(Control.ACMLDLL)]
        static extern float acml_fmax2(float a, float b);
        [DllImport(Control.ACMLDLL)]
        static extern double acml_dmax2(double a, double b);
        [DllImport(Control.ACMLDLL)]
        static extern int acml_imax2(int a, int b);
        [DllImport(Control.ACMLDLL)]
        static extern float acml_fmin2(float a, float b);
        [DllImport(Control.ACMLDLL)]
        static extern double acml_dmin2(double a, double b);
        [DllImport(Control.ACMLDLL)]
        static extern int acml_imin2(int a, int b);

        #endregion
        public static float Min(float a, float b, float c)
        {
            return acml_fmin3(a, b, c);
        }
        public static double Min(double a, double b, double c)
        {
            return acml_dmin3(a, b, c);
        }
        public static int Min(int a, int b, int c)
        {
            return acml_imin3(a, b, c);
        }
        public static float Max(float a, float b, float c)
        {
            return acml_fmax3(a, b, c);
        }
        public static double Max(double a, double b, double c)
        {
            return acml_dmax3(a, b, c);
        }
        public static int Max(int a, int b, int c)
        {
            return acml_imax3(a, b, c);
        }

        public static float Min(float a, float b)
        {
            return acml_fmin2(a, b);
        }
        public static double Min(double a, double b)
        {
            return acml_dmin2(a, b);
        }
        public static int Min(int a, int b)
        {
            return acml_imin2(a, b);
        }
        public static float Max(float a, float b)
        {
            return acml_fmax2(a, b);
        }
        public static double Max(double a, double b)
        {
            return acml_dmax2(a, b);
        }
        public static int Max(int a, int b)
        {
            return acml_imax2(a, b);
        }

    }
}
